<template>
  <div>
    <h3 class="attach-title">项目信息</h3>
    <hr />
    <div class="px-3">
      <table class="table table-sm table-borderless table-attach-detail">
        <colgroup>
          <col width="20%" />
          <col width="25%" />
          <col width="20%" />
          <col width="35%" />
        </colgroup>
        <tbody>
          <tr>
            <td>客户名称：</td>
            <td>{{ projectData.customer_name }}</td>
            <td>客户类型：</td>
            <td>{{ projectData.org_class_name }}</td>
          </tr>
          <tr>
            <td>身份证号：</td>
            <td>{{ projectData.lender_idcard }}</td>
            <td>联系地址：</td>
            <td>{{ projectData.address }}</td>
          </tr>
          <tr>
            <td>授信金额：</td>
            <td>{{ projectData.warranty_amount }} 万元</td>
            <td>授信期限：</td>
            <td>
              {{ projectData.loadDateCredit }}至{{ projectData.loadEndDateCredit }}（
              {{ projectData.period_credit }} 个月）
            </td>
          </tr>
          <tr>
            <td>婚姻状态</td>
            <td>{{ enumMarriageStatus[projectData.marriage_status] }}</td>
          </tr>
        </tbody>
      </table>
    </div>

    <attach-upload
      :tags="uploadTags"
      :view-mode="viewMode"
      :batch-no="queryId"
      v-bind="$listeners"
      @after-data="handleAfterData"
    >
      <template slot="header">
        <h3 class="attach-title">附件资料{{ currentStatus }}</h3>
        <hr />
      </template>
      <template slot="contract">
        <attach-contract
          :related-data="projectData"
          :view-mode="viewMode"
          :tag="contractTag"
          @get-contract="handleGetContract"
          @after-data="handleAfterData"
          @type-change="handleContractTypeChange"
          @success="handleContractSuccess"
        ></attach-contract>
      </template>
    </attach-upload>
  </div>
</template>

<script>
import AttachUpload from '@/bank/components/attach/Upload'
import AttachContract from '@/bank/views/business/hplimit/attach/AttachContract'
import { dataAdapter, enumMarriageStatus } from '@/bank/views/business/hplimit/enum'
const contractSlot = 'contract'
export default {
  components: {
    AttachUpload,
    AttachContract,
  },
  props: {
    queryId: String,
    updateAttachStatus: Boolean,
    viewMode: { type: Boolean, default: true },
  },
  data() {
    return {
      enumMarriageStatus,
      loading: false,
      projectData: {},
      isOnlineSign: 2,
      attachs: [],
      tableName: 'datum_one_county_industry',
      signStatus: 0,
      customerSignApproval: 0,
      currentStatus: 0,
      submitLoading: false,
    }
  },
  computed: {
    enumPersonalTags() {
      return [
        { tag: '主借人身份证正反面', required: false },
        {
          tag: '配偶身份证正反面',
          required: false,
          exit: +(this.projectData.marriage_status || '') !== 1,
        },
        { tag: '担保申请书', required: false },
        { tag: '委托合同', required: false, slot: 'contract' },
        {
          tag: '个人连带责任承诺书',
          required: false,
          exit: +(this.projectData.marriage_status || '') !== 1,
        },
        { tag: '乡村振兴普惠贷推荐表', required: false },
        { tag: '借款合同', required: false },
      ].filter(item => !item.exit)
    },
    uploadTags() {
      return this.viewMode
        ? [...this.enumPersonalTags, { tag: '其他', required: false }]
        : this.enumPersonalTags
    },
    relatedId() {
      return this.projectData.customer_related_id
    },
    contractTag() {
      const tag = this.uploadTags.find(it => it.slot === contractSlot) || {}
      return {
        tag: tag.tag,
        required: tag.required,
      }
    },
  },
  watch: {
    queryId: {
      handler: function () {
        this.getData()
      },
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    handleClose() {
      this.$emit('close')
    },
    getData() {
      this.loading = true
      this.$api
        .getData(this.$serviceName, this.tableName, { 'customer_related_id.eq': this.queryId })
        .then(res => {
          this.projectData = dataAdapter(res?.data?.[0] ?? {})
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleAfterData({ list, emit }) {
      if (!this.updateAttachStatus) return
      this.attachs = list
      const listObj = this.attachs.reduce((prev, curr) => {
        const tag = curr.attachment_type
        if (!prev[tag]) prev[tag] = []
        prev[tag].push(curr)
        return prev
      }, {})
      const isAllUpload = this.uploadTags.every(tag => {
        if (!tag.required) return true

        const isOnline = tag.slot === contractSlot && this.isOnlineSign === 1
        if (isOnline) {
          return this.customerSignApproval === 1
        }
        const atts = listObj[tag.tag]
        return atts && atts.length > 0
      })
      this.currentStatus = isAllUpload ? 1 : 0

      if (emit) {
        this.updateStatus()
      }
    },

    // 委托合同附件
    handleGetContract({ contract }) {
      this.isOnlineSign = +(contract.is_online_sign || 0)
      this.signStatus = +(contract.sign_status || 0)
      this.customerSignApproval = +(contract.customer_sign_approval || 0)
    },
    handleContractTypeChange(type) {
      this.isOnlineSign = type
      this.$emit('after-data', {})
      this.updateStatus()
    },
    handleContractSuccess() {
      this.signStatus = 1
      this.updateStatus()
    },

    // 更新项目附件状态
    updateStatus() {
      // 判断附件状态
      const listObj = this.attachs.reduce((prev, curr) => {
        const tag = curr.attachment_type
        if (!prev[tag]) prev[tag] = []
        prev[tag].push(curr)
        return prev
      }, {})
      const isAllUpload = this.uploadTags.every(tag => {
        const isOnline = tag.slot === contractSlot && this.isOnlineSign === 1
        if (isOnline) {
          return this.customerSignApproval === 1
        }
        if (!tag.required) return true
        const atts = listObj[tag.tag]
        return atts && atts.length > 0
      })
      const currentStatus = isAllUpload ? 1 : 0
      const attachStatus = +this.projectData.datum_status
      if (attachStatus === currentStatus) {
        return this.$emit('after-data', {})
      }

      // 更新状态
      this.$api
        .updateData({
          table: 'datum_one_county_industry',
          id: this.relatedId,
          data: {
            datum_status: currentStatus,
          },
        })
        .then(() => {
          // 观察：更改 props 对象值
          this.projectData.datum_status = currentStatus
        })
        .finally(() => {
          this.$emit('after-data', {})
        })
    },
  },
}
</script>

<style lang="scss" scoped>
.attach-title {
  font-size: 1.1rem;
  font-weight: bold;
}
</style>
